﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace BridgeShips {

    public class ShowShipsList : MonoBehaviour {

        private Vector3 m_ObjPosition = Vector3.zero;
        private bool m_IsMove = false;
        private Transform m_Content;
        private int m_MaxBtnCount;//按钮的最大数量
        private EmissionFlare m_EmissionFlare;
        private uint m_ID;

        private float m_LastTargetFindTime ;
        private List<Transform> m_shipNameList = new List<Transform>();
        void Start() {
            m_Content = transform.Find( "Scroll View/Viewport/Content" );
            m_EmissionFlare = new EmissionFlare();

        }

         void Update() {
            
            if (m_IsMove && !m_ObjPosition.Equals( Vector3.zero )) {
                m_IsMove = GameController.SimpleCameraControl.CameraTracePath( m_ObjPosition, m_IsMove );

            }
            if (m_ID <= 0)
                return;
            GameController.SimpleCameraControl.SetEnable( m_IsMove );

            if (m_EmissionFlare != null) {
                m_EmissionFlare.Update();
            }


            if (Time.time - m_LastTargetFindTime >= 4) {
                EnableFlare( m_ID, false );
            }

            
        }
        /// <summary>
        /// 每次调用前先清除所有按钮的点击事件，并清除
        /// </summary>
        void ClearAllBtns() {
            if (m_Content.childCount > 0) {
                for (int i = 0; i < m_Content.childCount; i++) {
                    m_Content.GetChild( i ).GetComponent<Button>().onClick.RemoveAllListeners();
                }
            }
        }


        //void ClearBtns(uint id)
        //{
        //    if (m_Content.childCount > 0)
        //    {
        //        for (int i = 0; i < m_Content.childCount; i++)
        //        {
        //            m_Content.GetChild(i).GetComponent<Button>().onClick.RemoveAllListeners();
        //        }
        //    }
        //}
        /// <summary>
        /// 增加或减少btn
        /// </summary>
        /// <param name="count"></param>
        void AddOrDecBtns( int count, List<uint> lst ) {
          
            //如果子节点的数量大于舟船总数量，删除多余的子节点
            if (m_Content.childCount > count) {
                for (int i = 0; i < m_Content.childCount; i++) {
                    if (i > count) {
                        m_shipNameList.Remove(m_Content.GetChild(i).transform);
                        Destroy( m_Content.GetChild( i ).gameObject );
                        
                    }
                }
            }
            //如果子节点数量小于舟船总数量
            else if (m_Content.childCount < count) {
                for (int i = 0; i < count; i++) {
                    if (i >= m_Content.childCount) {
                        GameObject go = Instantiate( Resources.Load( "Prefabs\\ShowShipIDBtn" ) ) as GameObject;
                        go.transform.SetParent( m_Content );
                        go.transform.GetComponent<RectTransform>().localScale = Vector3.one;
                        go.transform.GetComponent<RectTransform>().anchoredPosition3D = Vector3.zero;
                        m_shipNameList.Add(go.transform);
                    }
                }
            }
            //给子节点添加点击事件和添加文字
            for (int i = 0; i < m_Content.childCount; i++) {
                uint id = ShipsDictionary.Instance.HashCodeConvert( lst[i] );
                m_Content.GetChild( i ).GetComponentInChildren<Text>().text = /*"舟船名字：" +*/ id.ToString()+"号舟";
                uint num = lst[i];
                m_Content.GetChild( i ).GetComponent<Button>().onClick.AddListener( () => { OnBtnClick( num ); } );
                var m_shipType = GameFunc.Instance.m_ShipTypes;
                var icon = m_Content.GetChild(i).Find("icon");
                if (m_shipType==ShipTypes.StraddleType)
                {
                    icon.Find("straddleType").gameObject.SetActive(true);
                    icon.Find("lineType").gameObject.SetActive(false);
                }
                else
                {
                    icon.Find("straddleType").gameObject.SetActive(false);
                    icon.Find("lineType").gameObject.SetActive(true);
                }
                m_Content.GetChild(i).Find("linkState/linking").gameObject.SetActive(false);
                m_Content.GetChild(i).Find("linkState/unlink").gameObject.SetActive(true);
            }
        }
        /// <summary>
        /// 显示所有的按钮
        /// </summary>
        public void ShowAllShipsBtn( List<uint> lst ) {
            //if (m_MaxBtnCount == lst.Count)
            //    return;
            //清除所有按钮的点击事件
            ClearAllBtns();
            m_MaxBtnCount = lst.Count;

            AddOrDecBtns( m_MaxBtnCount, lst );
        }
        /// <summary>
        /// 获取点击事件
        /// </summary>
        /// <param name="id"></param>
        void OnBtnClick( uint id ) {
            if(id != m_ID) {
                EnableFlare( m_ID, false );
            }
            EnableFlare( id ,true);
            m_LastTargetFindTime = Time.time;
        }

        public void EnableFlare( uint id,bool flare) {
            var entity = GameEntry.Instance.EntityManager.Get( id );
            if (entity != null) {
                m_ID = id;
                if (Input.GetKey( KeyCode.LeftControl ) && flare) {
                    m_IsMove = true;
                    m_ObjPosition = entity.Get().transform.position;
                }
                else {
                    var meshRender = entity.Get().GetComponentInChildren<MeshRenderer>();
                    if (meshRender != null) {
                        m_EmissionFlare.MakeFlare( flare, meshRender );
                    }
                }
            }

        }
        /// <summary>
        /// 修改相应的舟船状态显示
        /// </summary>
        /// <param name="id"></param>
        /// <param name="isLinking"></param>
        public void ChangeShipListState(uint id,bool isLinking) {
            if (m_shipNameList.Count<=0)
            {
                return;
            }
            foreach (var item in m_shipNameList)
            {
                
                if (item.GetComponentInChildren<Text>().text.Contains(id.ToString()))
                {
                    if (isLinking)
                    {
                        item.Find("linkState/linking").gameObject.SetActive(true);
                        item.Find("linkState/unlink").gameObject.SetActive(false);
                       
                    }
                    else
                    {
                        item.Find("linkState/linking").gameObject.SetActive(false);
                        item.Find("linkState/unlink").gameObject.SetActive(true);
                    }
                }
            }
        }
    }
}